package view;

import java.awt.Color;
import java.awt.Dimension;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;

import model.ChatMessage;
import model.ChatModel;
import controller.MetaDeckController;

@SuppressWarnings("serial")
public class ChatComponent extends JPanel {
	final private ChatModel model;
	private ChatMessage lastMessageDisplayed;
	final private JTextPane display;
	final private JTextField inputField;
	public ChatComponent(ChatModel tmodel) {
		super();
		this.model = tmodel;
		lastMessageDisplayed = null;
		setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
		
		display = new JTextPane();
		display.setEditable(false);
		display.setText("Welcome to MetaDeck!\n");
		inputField = new JTextField();
		inputField.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
		JScrollPane displayScroll = new JScrollPane(display, 
				JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		displayScroll.setPreferredSize(new Dimension(250, 580));
		add(displayScroll);
		add(inputField);
	}
	
	/** Taken from some website, appends a colored string to the display. */
	public void append(Color c, String s) { 
		if (c == null || s == null)
			return;
	    StyleContext sc = StyleContext.getDefaultStyleContext();
	    AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
	  
	    int len = display.getDocument().getLength(); // same value as getText().length();
	    display.setCaretPosition(len);  // place caret at the end (with no selection)
	    display.setCharacterAttributes(aset, false);
	    display.setEditable(true);
	    display.replaceSelection(s); // there is no selection, so inserts at caret
	    display.setEditable(false);
	}
	
	public JTextField getInputField() {
		return inputField;
	}
	public void updateDisplay() {
		int start = model.getMessageIndex(lastMessageDisplayed)+1;
		for(int i=start; i<model.getNumMessages(); i++) {
			ChatMessage msg = model.getMessage(i);
			Color nameColor = MetaDeckController.getInstance().getPlayerColor(msg.getSender());
			append(nameColor, msg.getSender() +": ");
			append(Color.BLACK, msg.getMessage()+'\n');
			lastMessageDisplayed = msg;
		}
		display.repaint();
	}
}
